<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="closed"
  >
    <el-tree
      ref="treeRef"
      :data="allPermission"
      show-checkbox
      :check-strictly="true"
      node-key="id"
      default-expand-all
      :props="defaultProps"
    >
    </el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">{{
            $t("msg.universal.cancel")
          }}</el-button>
        <el-button
          type="primary"
          @click="onConfirm"
        >{{ $t("msg.universal.confirm") }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { rolePermission,distributePermission } from "@/api/role";
import { permissionList } from '@/api/permission'
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { watchSwitchLang } from '@/utils/i18n'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String,
    required: true
  }
});
// tree 节点
const treeRef = ref(null)
// 属性结构配置
const defaultProps = {
  children: 'children',
  label: 'permissionName'
}
// 所有权限
const allPermission = ref([])
const getPermissionList = async () => {
  allPermission.value = await permissionList()
}
getPermissionList()
watchSwitchLang(getPermissionList)

// 获取当前用户角色的权限
const getRolePermission = async () => {
  const checkedKeys = await rolePermission(props.roleId);
  console.log(checkedKeys);
  // checkedKeys=>["1","1-1","1-2","1-3","2","2-1","3","4","5"]返回的是当前角色所有权限的key值
  treeRef.value.setCheckedKeys(checkedKeys);
};

watch(
  () => props.roleId,
  (val) => {
    if (val) getRolePermission();
  }
);

const emits=defineEmits(["update:modelValue"])

/**
 确定按钮点击事件
 */
const i18n = useI18n();
const onConfirm = async () => {
  await distributePermission({
    roleId: props.roleId,
    permissions: treeRef.value.getCheckedKeys()
  });
  ElMessage.success(i18n.t("msg.role.updateRoleSuccess"));
  closed();
};

const closed=()=>{
  emits("update:modelValue",false)
}

</script>

<style scoped lang="scss">

</style>